package com.littlebee.storysuper.utils;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ViewHolder {
    private final SparseArray<View> views;
    private View convertView;
    private int layoutId;

    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
        this.layoutId = layoutId;
        this.views = new SparseArray();
        this.convertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        this.convertView.setTag(this);
    }

    public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId) {
        return get(context, convertView, parent, layoutId, -1);
    }

    static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
        if(convertView != null && !convertView.getTag().equals("NoData")) {
            ViewHolder viewHelper = (ViewHolder)convertView.getTag();
            return viewHelper.layoutId != layoutId?new ViewHolder(context, parent, layoutId, position):viewHelper;
        } else {
            return new ViewHolder(context, parent, layoutId, position);
        }
    }

    public <T > View findViewById(int viewId) {

        return this.findView(viewId);
    }

    private <T> View findView(int viewId) {
        View view = (View)this.views.get(viewId);
        if(view == null) {
            view = this.convertView.findViewById(viewId);
            this.views.put(viewId, view);
        }

        return view;
    }

    public View getView() {
        return this.convertView;
    }
}
